package cn.tedu.boot52.controller;

import cn.tedu.boot52.entity.User;
import cn.tedu.boot52.entity.Weibo;
import cn.tedu.boot52.mapper.WeiboMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.util.calendar.LocalGregorianCalendar;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        //得到当前登陆的用户对象
        User user= (User)session.getAttribute("user");
        if (user==null){
            return 2;//当前用户未登录
        }

        System.out.println("weibo = " + weibo + ", picFile = " + picFile);
        String fileName=picFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
        //文件夹路径
        String dirPath="e:/upload/weibo";
        File dirFile=new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //文件的完整磁盘路径
        String filePath=dirPath+"/"+fileName;
        //保存文件
        picFile.transferTo(new File(filePath));
        //把图片路径添加到weibo对象中
        weibo.setUrl("/"+fileName);
        //把作者保存到weibo对象中,当前登录的用户昵称就是作者名
        weibo.setAuthor(user.getNick());
        //把用户ID添加到用户对象中
        weibo.setUserId(user.getId());
        //把当前的时间添加到weibo对象中,new Date()得到的是当前系统时间
        weibo.setCreated(new Date());

        //按微博信息保存到weibo表中
        mapper.insert(weibo);
        return 1;//代表发布成功
    }
    @RequestMapping("/select")
    public List<Weibo>select(){
        return mapper.select();
    }

    @RequestMapping("/selectById")
    public Weibo selectById(int id){
        return mapper.selectById(id);

    }
    @RequestMapping("/selectMyWeibo")
    public List<Weibo>selectMyWeibo(HttpSession session){
        User user= (User) session.getAttribute("user");

        return mapper.selectByUserId(user.getId());
    }

    @RequestMapping("/delete")
    public void delete(int id){
        //通过id查询微博详情
        Weibo weibo=mapper.selectById(id);
        //得到文件的磁盘路径
        String filePath="e:/upload/weibo"+weibo.getUrl();
        //删除文件
        new File(filePath).delete();
        //删除数据库中的数据
        mapper.delete(id);
    }
}
